#include "password.h"

//********************************************************************************
//通过密文获取盐值
//********************************************************************************
void get_salt(char *salt, char *passwd)
{
    printf("in get_Salt\n");
    printf("passwd = %s\n", passwd);
    int i, j;
    //取出 salt,i 记录密码字符下标,j 记录$出现次数
    for (i = 0, j = 0; passwd[i] && j != 3; ++i)
    {
        if (passwd[i] == '$')
            ++j;
    }
    strncpy(salt, passwd, i);
    //$6$QTMje.pRHnM2UEQ8$
}

//********************************************************************************
//给客户端发送盐值，让客户端本地加密
//********************************************************************************
void sendSaltToClient(int peerfd, char *salt)
{
    //先发长度
    train_t train;
    train.len = strlen(salt);
    strcpy(train.data, salt);
    send(peerfd, &train, train.len + 4, MSG_WAITALL);
}

//********************************************************************************
//检查密码正确性
//********************************************************************************
int checkPasswd(int peerfd)
{
    while (1)
    {
        // 1.接收用户名
        ssize_t retval = 0;
        int lenOfUsername;
        retval = recv(peerfd, &lenOfUsername, 4, MSG_WAITALL);
        if(retval == 0)return -1;
        char username[50] = {0};
        recv(peerfd, username, lenOfUsername, 0);
        printf("username = %s\n", username);

        // 2.发送盐值，以供客户端加密
        struct spwd *sp = NULL;
        // 2.1获取盐值
        char flag = 0;
        if ((sp = getspnam(username)) == NULL)
        {
            send(peerfd,&flag,1,0);
            continue;
        }
        else
        {
            flag = 1;
            send(peerfd,&flag,1,0);
        }

        char salt[50] = {0};
        get_salt(salt, sp->sp_pwdp);
        sendSaltToClient(peerfd, salt);

        printf("salt = %s ,send salt finish\n", salt);
        // 3.接收密文
        int lenOfPasswd = 0;
        retval = recv(peerfd, &lenOfPasswd, 4, MSG_WAITALL);
        if(retval == 0)return -1;
        char passwd[200] = {0};
        recv(peerfd, passwd, lenOfPasswd, MSG_WAITALL);

        printf("miwen : %s\n", passwd);

        // 4.验证密文正确性
        if (strcmp(passwd, sp->sp_pwdp) == 0)
        {
            flag = 1;
            send(peerfd,&flag,1,0);
            break;
        }
        else
        {
            flag = 0;
            send(peerfd,&flag,1,0);
        }
    }
    return 0;
}
